extends Node2D

@onready var soundPlayersParent = $SoundPlayersParent
@onready var musicPlayersParent = $MusicPlayersParent

const TETROMINO_MOVE = "TetrominoMoveSound"
const TETROMINO_ROTATE = "TetrominoRotateSound"
const TETROMINO_REACH_BOTTOM = "TetrominoReachBottom"
const DESTROY_LINE = "DestroyLineSound"
const CANT_DO = "CantDoSound"
const CLICK = "Click"
const GAMING_BG = "GamingBgMusic"


func _ready():
	GlobalSignals.PLAY_SOUND.connect(PLAY_SOUND_handler)
	GlobalSignals.PLAY_MUSIC.connect(PLAY_MUSIC_handler)
	GlobalSignals.STOP_PLAY_MUSIC.connect(STOP_PLAY_MUSIC_handler)
	
	
func _exit_tree():
	GlobalSignals.PLAY_SOUND.disconnect(PLAY_SOUND_handler)
	GlobalSignals.PLAY_MUSIC.disconnect(PLAY_MUSIC_handler)
	GlobalSignals.STOP_PLAY_MUSIC.disconnect(STOP_PLAY_MUSIC_handler)
	
	
func PLAY_SOUND_handler(soundName):
	var soundPlayerCount = soundPlayersParent.get_child_count()
	for index in range(soundPlayerCount):
		var soundPlayer:AudioStreamPlayer = soundPlayersParent.get_child(index) as AudioStreamPlayer
		if soundPlayer.playing: continue
		
		soundPlayer.stream = Global.getSoundStream(soundName)
		soundPlayer.play()
		break
		
		
func STOP_PLAY_MUSIC_handler(playerId):
	var targetPlayer:AudioStreamPlayer = musicPlayersParent.get_child(playerId) as AudioStreamPlayer
	targetPlayer.stop()
	

func stopAllMusic():
	var musicPlayerCount = musicPlayersParent.get_child_count()
	for index in range(musicPlayerCount):
		var musicPlayer:AudioStreamPlayer = musicPlayersParent.get_child(index) as AudioStreamPlayer
		musicPlayer.stop()
		

func PLAY_MUSIC_handler(musicName):
	var musicPlayerCount = musicPlayersParent.get_child_count()
	for index in range(musicPlayerCount):
		var musicPlayer:AudioStreamPlayer = musicPlayersParent.get_child(index) as AudioStreamPlayer
		if musicPlayer.playing: continue
		
		musicPlayer.stream = Global.getSoundStream(musicName)
		musicPlayer.play()
		break
		

func playMusic(musicName):
	var playerId
	
	var musicPlayerCount = musicPlayersParent.get_child_count()
	for index in range(musicPlayerCount):
		var musicPlayer:AudioStreamPlayer = musicPlayersParent.get_child(index) as AudioStreamPlayer
		if musicPlayer.playing: continue
		
		musicPlayer.stream = Global.getSoundStream(musicName)
		musicPlayer.play()
		playerId = index
		
	return playerId
		
	
